package com.uchedao.seller.ui.car.publish;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.uchedao.seller.R;
import com.uchedao.seller.manager.ActivityManager;
import com.uchedao.seller.ui.baidu.BaseFragForBaidu;
import com.uchedao.seller.ui.car.base.BasePublishActivity;
import com.uchedao.seller.ui.car.publish.fragment.AccidentCoverFragment;
import com.uchedao.seller.ui.car.publish.fragment.EngineFragment;
import com.uchedao.seller.ui.car.publish.fragment.FireFragment;
import com.uchedao.seller.ui.car.publish.fragment.GuiseFragment;
import com.uchedao.seller.ui.car.publish.fragment.InteriorFragment;
import com.uchedao.seller.ui.car.publish.fragment.OutFuncFragment;
import com.uchedao.seller.ui.car.publish.fragment.PaintSurfaceFragment;
import com.uchedao.seller.ui.car.publish.fragment.PaintThicknessFragment;
import com.uchedao.seller.ui.car.publish.fragment.ReinforcementFragment;
import com.uchedao.seller.ui.car.publish.fragment.SkeletonFragment;
import com.uchedao.seller.ui.car.publish.fragment.WaterDipFragment;
import com.uchedao.seller.util.T;

/**
 * 发布3-检测项目
 */
public class PublishDetectActivity extends BasePublishActivity {

    private RelativeLayout rlContent;
    private RadioButton[] rbItems;
    private Button btnAllOk;

    private int pageIndex;  // 当前检测项
    private int pageCount;  // 检测项总数
    private String[] testItems;
    private BaseFragForBaidu fragment;

    private boolean[] completedItems; // 记录各项检测是否完成

    @Override
    protected String getActivityTag() {
        return "PublishDetectActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_publish_detect;
    }

    @Override
    protected void initView() {
        initToBar("检测");
        initBottomBar();
        rlContent = (RelativeLayout) findViewById(R.id.rlPublishContent);
        btnAllOk = (Button) findViewById(R.id.btnCheckAllOK);

        testItems = getResources().getStringArray(R.array.publish_test_items);
        pageIndex = -1;
        pageCount = testItems.length;
        completedItems = new boolean[pageCount];

        rbItems = new RadioButton[pageCount];
        rbItems[0] = (RadioButton) findViewById(R.id.rbTestItem1);
        rbItems[1] = (RadioButton) findViewById(R.id.rbTestItem2);
        rbItems[2] = (RadioButton) findViewById(R.id.rbTestItem3);
        rbItems[3] = (RadioButton) findViewById(R.id.rbTestItem4);
        rbItems[4] = (RadioButton) findViewById(R.id.rbTestItem5);
        rbItems[5] = (RadioButton) findViewById(R.id.rbTestItem6);
        rbItems[6] = (RadioButton) findViewById(R.id.rbTestItem7);
        rbItems[7] = (RadioButton) findViewById(R.id.rbTestItem8);
        rbItems[8] = (RadioButton) findViewById(R.id.rbTestItem9);
        rbItems[9] = (RadioButton) findViewById(R.id.rbTestItem10);
        rbItems[10] = (RadioButton) findViewById(R.id.rbTestItem11);
        rbItems[0].setChecked(true);
        switchTestItem(0);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        btnAllOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                oneKeyOK(pageIndex);
            }
        });
        btnButtomSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                save(pageIndex);
                ActivityManager.getInstance().clearAllActivity(null);
            }
        });
        btnBottomNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextItem();
            }
        });

        for(int i=0; i<pageCount; i++)
            rbItems[i].setOnCheckedChangeListener(new OnTestItemSwitchListener(i));
    }

    /**
     * 下一步
     */
    public void nextItem() {
        if(pageIndex >= (pageCount-1)) {
            // 已到最后一个检测项目
            save(pageCount-1);

            for(int i=0; i<pageCount; i++)
                if(!completedItems[i]) {
                    T.showShort(PublishDetectActivity.this, testItems[i] + "检测未完成");
                    rbItems[i].setChecked(true);
                    return;
                }

            // 检测项全部完成
            startActivity(new Intent(PublishDetectActivity.this, PublishPhotoActivity.class));
            finish();
        } else {
            rbItems[pageIndex+1].setChecked(true);
        }
    }

    /**
     * 切换检测项目
     */
    public void switchTestItem(int index) {
        if(pageIndex == index)
            return;

        save(pageIndex);

        tvTopTitle.setText(testItems[index] + "检测");
        if (index < (pageCount - 1))
            btnBottomNext.setText("下一步:" + testItems[index + 1] + "检测");
        else
            btnBottomNext.setText("下一步:车辆照片");

        pageIndex = index;

        switch(index) {
            case 0:
                toChildFragment(new PaintThicknessFragment());
                break;
            case 1:
                toChildFragment(new PaintSurfaceFragment());
                break;
            case 2:
                toChildFragment(new GuiseFragment());
                break;
            case 3:
                toChildFragment(new InteriorFragment());
                break;
            case 4:
                toChildFragment(new OutFuncFragment());
                break;
            case 5:
                toChildFragment(new EngineFragment());
                break;
            case 6:
                toChildFragment(new AccidentCoverFragment());
                break;
            case 7:
                toChildFragment(new ReinforcementFragment());
                break;
            case 8:
                toChildFragment(new SkeletonFragment());
                break;
            case 9:
                toChildFragment(new WaterDipFragment());
                break;
            case 10:
                toChildFragment(new FireFragment());
                break;
        }

        if(index == 0)
            btnAllOk.setVisibility(View.GONE);
        else
            btnAllOk.setVisibility(View.VISIBLE);
    }

    public void save(int index) {
        if(index>=0 && index<pageCount)
            completedItems[index] = ((ICallback) fragment).save();

        if(index>=0 && index<pageCount) {
            if (!completedItems[index]) {
                T.showShort(this, testItems[index] + "检测未完成");
                rbItems[index].setBackgroundResource(R.drawable.btn_circle_checked);
            } else {
                rbItems[index].setBackgroundResource(R.drawable.btn_circle_selected);
            }
        }
    }

    /**
     * 是否有空项(不包括第一个检测项)
     */
    public boolean noEmptyTerm(int index) {
        if(index>=1 && index<pageCount)
            return ((ICallback) fragment).noEmptyTerm();
        return true;
    }

    /**
     * 一键正常(不包括第一个检测项)
     */
    public void oneKeyOK(int index) {
        if(index>=1 && index<pageCount)
            ((ICallback) fragment).checkAllOk();
    }

    /**
     * 前往子项片段
     */
    private void toChildFragment(BaseFragForBaidu instance) {
        fragment = instance;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.rlPublishContent, instance, TAG);
        transaction.addToBackStack((String) null);
        transaction.commit();
    }

    private class OnTestItemSwitchListener implements CompoundButton.OnCheckedChangeListener {
        private int index;
        public OnTestItemSwitchListener(int index) {
            this.index = index;
        }
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(!b)
                return;
            if(index == pageIndex)
                return;

            if(pageIndex>0 && pageIndex<pageCount && !noEmptyTerm(pageIndex)) {
                new AlertDialog.Builder(PublishDetectActivity.this)
                        .setMessage(testItems[pageIndex] + "检测还未完成，是否设置全部选项正常？")
                        .setOnKeyListener(new DialogInterface.OnKeyListener() {
                            @Override
                            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                                return true;
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                btnOnChecked(index);
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                oneKeyOK(pageIndex);
                                btnOnChecked(index);
                            }
                        }).show();
            } else {
                btnOnChecked(index);
            }
        }
    }

    public void btnOnChecked(int index) {
        rbItems[index].setBackgroundResource(R.drawable.btn_circle_checked);
//            rbItems[pageIndex].setSelected(true);
        switchTestItem(index);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(fragment != null)
            fragment.onActivityResult(requestCode, resultCode, data);
    }
}
